package com.study.spmongodb.controller;

import com.study.spmongodb.article.dao.CommentRepository;
import com.study.spmongodb.article.po.Comment;
import com.study.spmongodb.article.po.Mydb;
import com.study.spmongodb.article.po.Personss;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/10 11:22
 */
@RestController
@RequestMapping("comment")
public class CommentController {

    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;


    @GetMapping("/")
    public Date saveComment() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            final Comment comment = new Comment();
            comment.setContent(String.format("%s今天-吐槽", RandomStringUtils.randomAlphanumeric(5)));
            comment.setPublishtime(new Date());
            comment.setUserid("" + i);
            comment.setNickname(String.format("%s_name", i));
            comment.setCreatedatetime(LocalDateTime.now());
            comment.setLikenum(i * 10);
            comment.setReplynum(i * 5);
            comment.setState("1");
            comment.setParentid(i + "");
            comment.setArticleid(i + "");
            TimeUnit.SECONDS.sleep(2);

            final Mydb mydb = new Mydb();
            mydb.setName(String.format("%s今天-吐槽", RandomStringUtils.randomAlphanumeric(5)));
            mydb.setCd(new Date());

            Personss person = new Personss();
            person.setAge(i);
            person.setFirstName(RandomStringUtils.randomAlphanumeric(5));
            person.setLastName("lastName");
            mongoTemplate.insert(person);
        }
        return new Date();
    }

    @GetMapping("/all")
    public Object list() {
        Query query = new Query();
        /*query.with(Sort.by(
                Sort.Order.desc("createdatetime")
                )
        );*/
        final List<Comment> comments = mongoTemplate.find(query, Comment.class);
        final List<Comment> all = mongoTemplate.findAll(Comment.class);
        System.out.println("查询到的分页中的条数:" + comments.size());
        comments.stream().forEach(System.out::println);
        return all;
    }
}
